
from flask import render_template, session, jsonify, current_app, g
from flask import request
# 测试
from info import constants
from info.constants import CLICK_RANK_MAX_NEWS
from info.modules.index import index_blu
from info.models import User, News, Category
from info.response_code import RET
from info.utils.common import user_login_data


@index_blu.route('/')
@user_login_data
def index():
    user=g.user
    print(user)
    news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    if not news_list:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在！")
    categories = Category.query.all()
    if not categories:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在！")
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 获取到当前登录用户的id
    # 右侧新闻排行
    # 按照点击量排序查询出点击最高的前10条新闻
    # 将对象字典添加到列表中
# 返回数据

    data = {
            'user':user.to_dict()if user else None,
            "news_dict_list":news_list,
            "category_list":category_list
        }
    return render_template("news/index.html",data=data)

@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据

    :return:
    """

    cid=int(request.args.get("cid",1))
    page=int(request.args.get("page",1))
    per_page=int(request.args.get("perpage",10))
    if not all([cid,per_page]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数为空")
    filter=[]
    if cid!=1:
        filter.append(News.category_id==cid)
    paginate=News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page,False)
    items=paginate.items
    current_page=paginate.page
    total_page=paginate.pages

    news_dict_list=[]
    for item in items:
        news_dict_list.append(item.to_basic_dict())
    data={
        'current_page':current_page,
        'total_page':total_page,
        'news_dict_list':news_dict_list,
        'cid':cid
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)
    # 1. 获取参数,并指定默认为最新分类,第一页,一页显示10条数据

    # 2. 校验参数

	  # 默认选择最新数据分类

    # 3. 查询数据

    # 将模型对象列表转成字典列表
	#返回数据

